package org.xurui.sxl.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.sxl.protocol.cache.ConcurrentMapCache;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 家庭 MAC 地址设置
 */
@Slf4j
public class CmdCodec_HOMEMAC implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.HOMEMAC.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return true;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //设备回复格式：*XX,YYYYYYYYYYYYYYY,V4,HOMEMAC,seq,para,HHMMSS,S,latitude,D,longitude,G,speed,pdop,DDMMYY,tracker_status#
        //设备回复示例：*TE,7893267561,V4,HOMEMAC,130305,1,B4:0B:44:CA:D4:8A,130306,V,2234.3061,N,11351.6677,E,0.85,0.76,160819,FDFFFDFF#
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        String[] payloadArr = payload.replaceAll("\\*","").split(",");
        String deviceId = payloadArr[1];
        report.setDeviceId(deviceId);
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(deviceId+"_"+CommandEnum.HOMEMAC.name()+"_"+payloadArr[4]);
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = deviceId+"_"+payloadArr[4];
        }

        report.setFunctionId(CommandEnum.HOMEMAC.name());
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        String[] paraArr= Arrays.copyOfRange(payloadArr,4,payloadArr.length-10);
        String para="";
        for (int i=1;i<paraArr.length;i++){
            // System.out.println(paraArr[i]);
            if(i==1){
                para=paraArr[i];
            }else{
                para=para+","+paraArr[i];
            }
        }
        int j=4+paraArr.length-1;

        Map<String, Object> properties = new HashMap<>();
        properties.put("para",para);
        properties.put("uptime",payloadArr[j+1]);
        properties.put("s",payloadArr[j+2]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[j+3],"lat"));
        properties.put("d",payloadArr[j+4]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[j+5],"lon"));
        properties.put("g",payloadArr[j+6]);
        properties.put("speed", NumberUtils.parseDouble(payloadArr[j+7]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[j+8]));
        properties.put("upday", payloadArr[j+9]);
        String trackerStatusHex = payloadArr[j+10];


        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setOutput(properties);

        //TODO 更新状态
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //格式：*XX,YYYYYYYYYYYYYYY,HOMEMAC,HHMMSS,NUM,MAC1,MAC2,,,,,,,,,,#
        //例子：*TE,7893267561,HOMEMAC,130305,1,B4:0B:44:CA:D4:8A#
        //例 2 *TE,7893267561,HOMEMAC,130305,2,B3:0B:44:CA:D4:8A,B4:0B:44:CA:D4:8A#
        //例 3 *TE,7893267561,HOMEMAC,130305,0,# //清空
        //参数说明：NUM 个数，1-6，最多 6 个
        //参数说明：MAC WIFIMAC 地址，字母大写
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            int num=0;
            if(paramsMap.get("num")!=null && !paramsMap.get("num").equals("")) {
                num=Integer.parseInt(paramsMap.get("num").toString());
            }
            String[] mac = new String[]{};
            if(paramsMap.get("mac")!=null && !paramsMap.get("mac").equals("")) {
                mac=paramsMap.get("mac").toString().split(",");
            }
            if(num!=0){
                if(mac.length==0){
                    log.error("WIFIMAC 地址为空请重新填写");
                    return null;
                }
                if(mac.length>0){
                    if(mac.length!=num){
                        log.error("该参数个数与WIFIMAC地址长度不一样请重新填写WIFIMAC地址");
                        return null;
                    }
                }
            }

            //String[] mesArr= paramsMap.toString().split(",");

            String time = SxlMessageUtils.getTimeHHMMSS();//DateFormatUtils.format(new Date(),"HHmmss");
            /*StringBuffer sb = new StringBuffer();
            sb.append("*");
            sb.append(zzs);//TODO 需要修改成根据设备动态加载
            sb.append(",");
            sb.append(message.getDeviceId());
            sb.append(",");
            sb.append(CommandEnum.HOMEMAC.name());
            sb.append(",");
            sb.append(time);
            sb.append(",");
            //sb.append(num);
            sb.append(mac.length);
            if(num>0){
                for (int i=1;i<mac.length;i++){
                    sb.append(",");
                    sb.append(mac[i]);
                }
            }else {
                sb.append(",");
            }

            sb.append("#");*/
            SxlMessageUtils.SxlCmd sxlCmd=SxlMessageUtils.SxlCmd.getInstance();
            sxlCmd.appendAndAddSeparator(zzs)
                .appendAndAddSeparator(message.getDeviceId())
                .appendAndAddSeparator(CommandEnum.HOMEMAC.name())
                .appendAndAddSeparator(time);
            if(num>0){
                sxlCmd.append(String.valueOf(mac.length));
                for (int i=0;i<mac.length;i++){
                    sxlCmd.append(SxlMessageUtils.CMD_SEPARATION)
                    .append(mac[i]);
                }
            }else{
                 sxlCmd.appendAndAddSeparator(String.valueOf(num));
            }


            ConcurrentMapCache.getInstance().set(message.getDeviceId()+"_"+CommandEnum.HOMEMAC.name()+"_"+time,message.getMessageId(),60*3*1000);
            //return EncodedMessage.simple(Unpooled.wrappedBuffer(sb.toString().getBytes()));

            return sxlCmd.buildEncodeMessage();

        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.WIFISCAN.name(),message);
            }
            return null;
        }

    }
}
